//
//  WSPlayViewController.m
//  GroupFourFM
//
//  Created by dllo on 15/12/22.
//  Copyright © 2015年 GroupFour. All rights reserved.
//

#import "WSPlayViewController.h"
#import "WSPlayView.h"
#import <AFNetworking.h>
#import "WSResource.h"
#import "WSTrackModel.h"
#import "WSPlayerFirstCell.h"
#import "WSPlayerSecondCell.h"
#import "WSAlbumInfoModel.h"
#import "WSPlayButton.h"
#import <UIButton+WebCache.h>
#import "WSTabBarPlayButton.h"
#import "WSPlayListViewController.h"
#import "WHAuthorDetailViewController.h"

@interface WSPlayViewController ()<UITableViewDataSource, UITableViewDelegate, WSPlayListViewControllerDelegate>

typedef enum : NSUInteger {
    MBAudioPlayTypeCircle,  //循环播放
    MBAudioPlayTypeRandom,  //随机播放
    MBAudioPlayTypeOneMusic,//单曲循环
    
} MBAudioPlayType;

@property (nonatomic, strong) WSPlayView *playerView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) WSAlbumModel *albumModel;

//定时器
@property (nonatomic, strong) NSTimer *playTimer;

@property (nonatomic, strong) WSAlbumInfoModel *albumInfoModel;

@property (nonatomic, strong) NSMutableArray *albumsInfoArray;

@property (nonatomic, assign) NSInteger num;

@property (nonatomic, assign) NSInteger playType;

@end

@implementation WSPlayViewController

+ (instancetype)sharaMusicPlayer {

    static WSPlayViewController *playViewC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playViewC = [[WSPlayViewController alloc] init];
    });
    
    return playViewC;
}

- (void)viewWillAppear:(BOOL)animated {

    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"album_album_mask"] forBarMetrics:UIBarMetricsCompactPrompt];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2=imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        imageView2.hidden=YES;
                    }
                }
            }
        }
    }
    [self.tableView scrollsToTop];
}

- (void)viewDidDisappear:(BOOL)animated {

    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsCompactPrompt];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WHITE;
    [self createTableView];
    
    //初始化播放器
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    self.player.volume = 0.5;
    
    //返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, 40, 40, 30);
    backButton.backgroundColor = CLEAR;
    backButton.tintColor = WHITE;
    [backButton setImage:[[UIImage imageNamed:@"navidrop_arrow_down_n"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    moreButton.frame = CGRectMake(0, 0, 40, 30);
    moreButton.backgroundColor = CLEAR;
    [moreButton setImage:[UIImage imageNamed:@"icon_more_n"] forState:UIControlStateNormal];
    [moreButton setImage:[UIImage imageNamed:@"icon_more_h"] forState:UIControlStateHighlighted];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];
    
    
    [self.playerView.upButton addTarget:self action:@selector(upButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.listButton addTarget:self action:@selector(listButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    // 滑动条
    [self.playerView.progressSlider addTarget:self action:@selector(progressSliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.playerView.historyButton addTarget:self action:@selector(historyButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    // 切换播放模式
    // 播放模式
    self.num = 2;
    self.playType = MBAudioPlayTypeCircle;
    [self.playerView.playType addTarget:self action:@selector(changePlayType:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)createTableView {
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 100;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[WSPlayerFirstCell class] forCellReuseIdentifier:@"firstCell"];
    [self.tableView registerClass:[WSPlayerSecondCell class] forCellReuseIdentifier:@"secondCell"];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(@0);
    }];
    
    
    self.playerView = [[WSPlayView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 0.85)];
    self.tableView.tableHeaderView = self.playerView;
    
}

#pragma mark - tableView delegate && dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        
        return 2;
    }
    else if (section == 2) {
    
        if (_albumsInfoArray.count > 3) {
            return 3;
        }
        else {
        
            return _albumsInfoArray.count;
        }
        
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    if (_albumsInfoArray.count == 0) {
        return 2;
    }
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    if (section == 0) {
        return 10;
    }
    return 40;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    if (section == 1) {
        
        return @"所属专辑";
    }
    else if (section == 2) {
    
        return @"相关专辑";
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
    
        if (indexPath.row == 0) {
            
            WSPlayerFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"firstCell"];
            cell.trackModel = _albumModel;
            
            return cell;
        }
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.textLabel.text = _albumModel.intro;
        cell.textLabel.numberOfLines = 3;
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.textLabel.textColor = [UIColor colorWithRed:0.58 green:0.58 blue:0.58 alpha:1];
        
        return cell;
    }
    WSPlayerSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:@"secondCell"];
    
    if (indexPath.section == 2) {
        
        cell.model = [_albumsInfoArray objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else {
    
        cell.model = _albumInfoModel;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        
        [self.delegate pushNextViewC:self.albumInfoModel.uid title:self.albumInfoModel.title];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    if (indexPath.section == 2) {
        WSAlbumInfoModel *albumInfo = [self.albumsInfoArray objectAtIndex:indexPath.row];
        [self.delegate changePageData:albumInfo.albumId title:albumInfo.title];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma makr 上一曲
- (void)upButtonAction:(UIButton *)button {

    if (self.indexRow != 0) {
        
        self.indexRow = (self.indexRow - 1);
    }
    else
    {
        self.indexRow = self.allMusicArray.count - 1;
    }
    
    WSTrackModel *sing = [self.allMusicArray objectAtIndex:self.indexRow];
    self.song_id = sing.trackId;
}

#pragma mark 下一曲
- (void)nextButtonAction:(UIButton *)button {
    
    switch (self.playType) {
        case MBAudioPlayTypeCircle:
        {
            
            self.indexRow = (self.indexRow + 1)%self.allMusicArray.count;
            
            WSTrackModel *singleM = [self.allMusicArray objectAtIndex:self.indexRow];
            self.song_id = singleM.trackId;
            
            self.navigationItem.title = singleM.title;
        }
            
            break;
            
        case MBAudioPlayTypeRandom:
        {
            //随机播放
            //NSLog(@"走了MBAudioPlayTypeRandom:");
            [self randomWithTimes:5];
            
            if (self.indexRow == self.allMusicArray.count) {
                
                self.indexRow = 0;
            }
            WSTrackModel *m = [self.allMusicArray objectAtIndex:self.indexRow];
            self.song_id = m.trackId;
            self.navigationItem.title = m.title;
        }
            
            break;
            
        case MBAudioPlayTypeOneMusic:
        {
            [self getData];
        }
            break;
            
        default:
            break;
    }
//    self.indexRow = (self.indexRow + 1)%self.allMusicArray.count;
//    
//    WSTrackModel *singleM = [self.allMusicArray objectAtIndex:self.indexRow];
//    self.song_id = singleM.trackId;
}

#pragma mark - 随机算法
-(void)randomWithTimes:(NSInteger)num
{
    NSInteger randomMusic = arc4random() % self.allMusicArray.count;
    
    //NSLog(@"随机值为：%ld",randomMusic);
    if (_indexRow == randomMusic && self.allMusicArray.count != 1) {
        //防止递归死循环
        if (num != 0) {
            num--;
            [self randomWithTimes:num];
            return;
        }else
        {
            randomMusic++;
            //递归多次还一样，就强行设一个了（低概率事件）
            _indexRow = randomMusic;
        }
    }
    else
    {
        //正常情况
        _indexRow = randomMusic;
    }
}

#pragma mark 播放
- (void)playButtonAction:(UIButton *)button {
    
    if (self.player.state == STKAudioPlayerStatePlaying) {
        
        [self.player pause];
//        [self.playTimer invalidate];
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_play_n_p"] forState:UIControlStateNormal];
    }
    else if (self.player.state == STKAudioPlayerStatePaused) {
        
        [self.player resume];
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_h_p"] forState:UIControlStateNormal];
    }
    else {
        
        [self getData];
    }
}

#pragma mark 列表
- (void)listButtonAction:(UIButton *)button {
    
    WSPlayListViewController *playListVC = [[WSPlayListViewController alloc] init];
    playListVC.playArray = self.allMusicArray;
    playListVC.indexRow = self.indexRow;
    playListVC.delegate = self;
    playListVC.kind = @"播放列表";
    [self.navigationController pushViewController:playListVC animated:YES];
}

#pragma mark 进度
- (void)progressSliderAction:(UISlider *)slider {
    
    if (self.player) {
        
        [self.player seekToTime:self.playerView.progressSlider.value];
    }
    
}

#pragma mark - 切换播放模式
- (void)changePlayType:(UIButton *)btn
{
    if (self.num == 1) {
        self.playType = MBAudioPlayTypeCircle;
        //NSLog(@"当前是循环播放模式");
        [btn setBackgroundImage:[UIImage imageNamed:@"iconfont-xunhuan"] forState:(UIControlStateNormal)];
        self.num++;
    }
    else if (self.num == 2) {
        self.playType = MBAudioPlayTypeRandom;
        self.num ++;
        //NSLog(@"当前是随机播放模式");
        [btn setBackgroundImage:[UIImage imageNamed:@"iconfont-suijibofang-1"] forState:(UIControlStateNormal)];
    }
    else  if (self.num == 3) {
        self.playType = MBAudioPlayTypeOneMusic;
        self.num = 1 ;
        [btn setBackgroundImage:[UIImage imageNamed:@"iconfont-danquxunhuan-2"] forState:(UIControlStateNormal)];
        //NSLog(@"当前是单曲循环模式");
    }

}

#pragma mark 历史
- (void)historyButtonAction:(UIButton *)button {
    
    
}

//歌曲id
-(void)setSong_id:(NSInteger)song_id
{
    if (_song_id == song_id) {
        
        [self.player resume];
        return;
    }
    
    _song_id = song_id;

    if (song_id != 0) {
        
        [self getData];
    }
//    if (_indexRow == 0) {
//        self.playerView.upButton.enabled = NO;
//    }
}

- (void)getData
{
    
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%ld", (long)self.song_id];
    
    [WSResource getDataWithURL:string block:^(id result) {
        
        NSMutableDictionary *dictionary = result;
        
        self.albumModel = [WSAlbumModel modelWithDictionary:dictionary];
        
        [self.player play:_albumModel.playUrl64];
#pragma mark - 记录播放过的音乐
        
        [[WSFMData shareFMDB] openDBandCreate];
        
        [[WSFMData shareFMDB] deleteByTrackId:_albumModel.trackId];
        [[WSFMData shareFMDB] insertTrackData:_albumModel];
        
        
        //给playView赋值
        [self.playerView.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:_albumModel.coverLarge] placeholderImage:PLACEHOLDER_IMAGE];
        [self.playerView.musicImageView sd_setImageWithURL:[NSURL URLWithString:_albumModel.coverLarge] placeholderImage:PLACEHOLDER_IMAGE];
        
        self.navigationItem.title = _albumModel.title;

//        self.uid = playData.uid;
        
        self.playTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
        
        //通知按钮换图片
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:[NSURL URLWithString:playData.coverLarge]];
        
        [self changeImageView];
        
        [WSResource getDataWithURL:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/playpage/11038183?albumId=%ld&device=iPhone&trackUid=%ld", self.albumModel.albumId, self.song_id] block:^(id result) {
            
            self.albumsInfoArray = [NSMutableArray array];
            for (NSDictionary *dic in [result objectForKey:@"associationAlbumsInfo"]) {
                WSAlbumInfoModel *model = [[WSAlbumInfoModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.albumsInfoArray addObject:model];
            }
            self.albumInfoModel = [[WSAlbumInfoModel alloc] init];
            [self.albumInfoModel setValuesForKeysWithDictionary:[result objectForKey:@"albumInfo"]];
            
            [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_h_p@2x.png"] forState:UIControlStateNormal];
            
            [self.tableView reloadData];
        } error:^(NSError *error) {
            
            
        }];
//        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_h_p@2x.png"] forState:UIControlStateNormal];
        
        
    } error:^(NSError *error) {
        
        
    }];
}

- (void)changeImageView {

    WSTabBarPlayButton *playButton = _tabbar.playButton;
    [playButton.musicBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:_albumModel.coverLarge] forState:UIControlStateNormal placeholderImage:PLACEHOLDER_IMAGE];
}

-(void)track {
    
    self.playerView.progressSlider.maximumValue = self.player.duration;//音乐总共时长
    self.playerView.progressSlider.value = self.player.progress;//当前进度
    
    //当前时长progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.playerView.timeLabelLeft.text = [NSString stringWithFormat:@"%02ld:%02ld", (long)proMin, (long)proSec];
    self.playerView.timeLabelRight.text = [NSString stringWithFormat:@"%02ld:%02ld",(long)durMin, (long)durSec];
    
    if (self.player.state == STKAudioPlayerStateStopped ) {
        [self nextButtonAction:nil];
        
        [self.playTimer invalidate];
    }
}


//返回
- (void)backButtonAction:(UIButton *)btn {
    
    WSTabBarPlayButton *playButton = _tabbar.playButton;
    [playButton.musicBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:_albumModel.coverLarge] forState:UIControlStateNormal placeholderImage:PLACEHOLDER_IMAGE];
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [playButton startCircle];
        
    }
    if (self.player.state == STKAudioPlayerStatePaused) {
        [playButton stopCircle];
        
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (scrollView.contentOffset.y < -100) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark WSPlayListViewConrtrollerDelegate
- (void)changePlayMusic:(NSInteger)song_id indexRow:(NSInteger)indexRow {

    self.indexRow = indexRow;
    self.song_id = song_id;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
